<script lang="ts" setup>
import { firstPartyApi } from '@/api/qis/firstParty'
import { OrganizationQualificationApi } from '@/api/qis/organizationqualification'
import { OrganizationStaffApi } from '@/api/qis/organizationstaff'
import { UserInfoApi } from '@/api/qis/userInfo'
import { ref, onMounted } from 'vue'
import { validatePassword, validatePhone, validateEmail } from './rules.ts'
import { defaultProps, handleTree } from '@/utils/tree'
import * as MenuApi from '@/api/system/menu'
import { useUserStore } from '@/store/modules/user'
import { getDefaultHighWaterMark } from 'stream'
import { useIcon } from '@/hooks/web/useIcon'
import { ProjectManagemenrApi } from '@/api/qis/projectmanagemenr/index.js'
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconLock = useIcon({ icon: 'ep:lock' })



import { dealTreeAddDisable } from '@/utils/tree-date-deal'
const getTreeList = async () => {
  // menuOptions.value = handleTree(await MenuApi.getSimpleMenusList())
  const res = handleTree(await MenuApi.getSimpleMenusList())
  res.forEach((item) => {
    if (item.name != '系统管理' && item.name != '基础设施') {
      menuOptions.value.push(item)
    }
  })

  getRoleListApi(userId.value)
}


const formLogin = ref()

const validateUserName = (rule: any, value: any, callback: any)=>{
  if(value != queryParams.value.loginName){
    callback('请输入正确的用户名')
}else {
  callback()
}

}


const dialogRules = {
  loginName:[{required: true, message: '请输入登录名', trigger: 'blur' },
  {max:50, message: '登录名长度不能超过50个字符', trigger: 'blur' },
  {min:3, message: '登录名长度不能小于3个字符', trigger: 'blur' },
  { pattern: /^[^\u4e00-\u9fa5]+$/, message: '登录名不能为汉字', trigger: 'blur' }
],
  password:[{ required: true, validator: validatePassword, trigger: 'blur' }],
}





const handleChangeTree = (value)=>{
  console.log(value,'value')

  queryParams.value.companyId = value.id
  queryParams.value.orgStaffName = value.id
}

const defaultProps1 = {
  children: 'children',
  label: 'name',
  value:'id'
}


const userRef = ref()

// 修改
const updateLogin = async () => {
  if(!formLogin.value) return 
  await formLogin.value.validate( async (valid)=>{
    if(valid){
      const res = await UserInfoApi.updatePasswordApi(loginData.loginForm)

if (res) {
  loginData.loginForm.password = ''
  loginData.loginForm.loginName = ''
  message.success('修改成功')

  loginDialog.value = false
}
    }
  })

}

const route = useRoute()
const id = route.query.id
const router = useRouter()

const bol = ref(false)
const userInfo = ref({})
const getUserInfo = async () => {
  const res = await UserInfoApi.getUserInfoDetail()

  // 是本人或者管理员
  if (!route.query.id || res.id == route.query.id || res.ruleCode == 'admin_qis') {
    bol.value = true
  } else {
    // 不是本人
    bol.value = false
  }
}

/** 展开/折叠全部 */
const handleCheckedTreeExpand = () => {
  const nodes = treeRef.value?.store.nodesMap
  for (let node in nodes) {
    if (nodes[node].expanded === menuExpand.value) {
      continue
    }
    nodes[node].expanded = menuExpand.value
  }
}

const menuExpand = ref(false) // 展开/折叠

const treeRef = ref() // 菜单树组件 Ref

/** 全选/全不选 */
const handleCheckedTreeNodeAll = () => {
  treeRef.value.setCheckedNodes(treeNodeAll.value ? menuOptions.value : [])
}

const ruleId = ref('') // 角色id

const handleRoleChange = async (value) => {
  queryParams.value.orgStaffId1 = ''
  queryParams.value.orgStaffId = ''
  queryParams.value.companyId = ''
  queryParams.value.name = ''
  const roleIdListArr = await UserInfoApi.getRoleIdApi()
  console.log(roleIdListArr.list, 'roleIdList')
  let selectItem = {}
  // treeRef.value.setCheckedKeys(roleIdListArr.list)
  
  // console.log(value,'value')
  roleList.value.forEach((item) => {
    // console.log(item.value, 'item.value')
    // console.log(value, 'value')
    if (item.value == value) {
      if(value == 'org_user'){
        // console.log('org_user1111')
      }
      selectItem = item
    }

    console.log(selectItem, 'selectItem')

  })
  roleIdListArr.list.forEach((v) => {
    console.log(v.label, 'v.label')
    // console.log(selectItem.label, 'selectItem.label')
    if (v.label.trim() == selectItem.label.trim()) {
      console.log(v, 'v')
      ruleId.value = v.value
    }
  })

  getRoleByIdListApi(ruleId.value)
  queryParams.value.roleCode = value
  if (value == 'org_user') {
    queryParams.value.isFromOrg = 1
  } else {
    queryParams.value.isFromOrg = 0
  }

  queryParams.value.orgStaffId = ''
  console.log(queryParams.value.orgStaffId, 'queryParams')

}

// 新增获取属性权限
const getRoleByIdListApi = async (id) => {
  const res = await UserInfoApi.getRoleByIdList(id)
  console.log(res)
  queryParams.value.menuIds = res
  // const echoIds = res

let  echoIds =  res.filter((item)=>item !=2772)
console.log(echoIds, 'echoIds')



  
const filterArr =  getLeafNodeIds(menuOptions.value)
const arr = []
console.log(filterArr, 'echoIds')
filterArr.forEach((item)=>{
  echoIds.forEach((v)=>{
    if(item == v){
        arr.push(v)
    }
  })
})

if (treeRef.value) {

treeRef.value.setCheckedKeys(

arr

  // [2819, 2820, 2821, 2822, 2823, 2824, 2825, 2826, 2865, 2866, 2867, 2772, 2868, 2869, 2870, 2812, 2813]

  // [2819, 2820, 2821, 2822, 2823, 2824, 2825, 2826, 2865, 2866, 2867, 2868, 2869, 2870, 2812, 2813]
)


}
}

function getLeafNodeIds(data) {
    /**
     * 获取所有叶子节点的 id
     * @param {Array|Object} data - 原始数据（JSON 格式）
     * @return {Array} 叶子节点的 id 数组
     */
    let leafNodeIds = [];

    function traverse(node) {
        if (Array.isArray(node.children) && node.children.length > 0) {
            // 如果是父级节点，递归遍历其子节点
            node.children.forEach(child => traverse(child));
        } else {
            // 如果是叶子节点，将其 id 添加到结果中
            leafNodeIds.push(node.id);
        }
    }

    if (Array.isArray(data)) {
        data.forEach(node => traverse(node));
    } else if (typeof data === 'object' && data !== null) {
        traverse(data);
    }

    console.log(leafNodeIds,'leafNodeIds')
    return leafNodeIds;
}


const handleFocus =async  (value)=>{
  console.log(value,'value')
  const res = await OrganizationQualificationApi.getOrganizationQualificationPage({name:value,pageNo:1,pageSize:1000})
  console.log(res,'res')
  CJJGName.value = res.list
}

onMounted(() => {
  getDetail()
  getUserInfo()
  getTreeList()

  if(route.query.id){
    route.meta.title = '编辑用户管理'
  }else {
    route.meta.title = '新增用户管理'
  }
})

const queryParams = ref({
  password: '',
  isNextReset: 0,
  menuIds: [],
  isValid:1
})

const upDateUserApi = async () => {
  queryParams.value.menuIds = menuOptions.value
  console.log(queryParams.value.menuIds, 'queryParams.value.menuIds')
  const res = await UserInfoApi.updateUserInfo(queryParams.value)
}

const menuOptions = ref<any[]>([]) // 菜单树形结构

const goBack = () => {
  router.back()
}

// 校验密码是否一致
const validatePasswordConfirm = (rule, value, callback) => {
  if (value !== queryParams.value.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 获取甲方单位
const JFList = ref([])
const getJFDW = async () => {
  const res = await UserInfoApi.getUserInfoPage({pageNo:1,pageSize:10000})
  JFList.value = res.list
}

// 登录次数解锁
const loginUnlock = async () => {
  const res = await UserInfoApi.putLoginUnlock(queryParams.value.loginName)
  message.success('解锁成功')
}
const userId = ref('')
const getDetail = async () => {
  if (id) {
    // 编辑
    const data = await UserInfoApi.getUserInfo(id)
    console.log(data,'data')
    queryParams.value = data
    console.log(queryParams.value, 'queryParams.value = data')
    queryParams.value.orgStaffId1 = data.companyName
    userId.value = data.userId
    
  }
}

const message = useMessage()
const handleAdd = async () => {
  let menuIds = [
    ...(treeRef.value.getCheckedKeys(false) as unknown as Array<number>), // 获得当前选中节点
    ...(treeRef.value.getHalfCheckedKeys() as unknown as Array<number>) // 获得半选中的父节点
  ]
  queryParams.value.menuIds = menuIds
  if(!userRef.value)  return 
 await  userRef.value.validate(async (valid)=>{
  if(valid){
    if (id) {
    try {
      // 编辑
      const data = await UserInfoApi.updateUserInfo(queryParams.value)
      console.log(data)
      message.success('编辑成功')
      goBack()
      // upDateUserApi()
    } catch (error) {
      console.log(error, 'error')
    }
  } else {
    // 新增
    try {
      queryParams.value
      const data = await UserInfoApi.createUserInfo(queryParams.value)
      console.log(data)
      message.success('新增成功')
      goBack()
      // upDateUserApi()
    } catch (error) {
      console.log(error, 'error')
    }
  }
  }
 })

}

const roleList = ref([])

// const userId = userStroe.$state.user.id

const getRoleListApi1 = async () => {
  const data = await UserInfoApi.getRoleList1()
  roleList.value = data.list
}

// 承检机构名称下拉
const companyList = ref([
  // { label: '单位1', value: '1' },
  // { label: '单位2', value: '2' },
  // { label: '单位3', value: '3' }
])
// 是否有效下拉
const isValidList = ref([
  { label: '是', value: 1 },
  { label: '否', value: 0 }
])

const restaurants = ref<any[]>([])

const querySearch = (queryString: string, cb: any) => {
  console.log(queryString,'queryString')
  // restaurants.value.forEach((item,index)=>{
  //   item.value = item.id
  // })
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  // call callback function to return suggestions
  cb(results)
}

const createFilter = (queryString: string) => {
  return (restaurant) => {
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
  }
}

const handleSelect = (item: any) => {
  console.log('选择',item)
  queryParams.value.orgStaffId = item.id
  queryParams.value.isFromOrg = 1
}

const  handleInput = (value)=>{
  console.log('输入','value')
  queryParams.value.isFromOrg = 0
  queryParams.value.companyName = value
  queryParams.value.orgStaffId = ''

}

const isClick = ref(0)
const searchIcon = () => {
  isClick.value = 1
}

const getCJJGList = async (id) => {
  const data = await OrganizationStaffApi.getJgrypageApi({pageNo:1,pageSize:10000,orgId:id})
  companyList.value = data.list.map((item: any) => {
    return {
      label: item.name,
      value: item.id
    }
  })

  restaurants.value = companyList.value.map((item) => {
    console.log(item)
    return { value: item.label ,id: item.value }
  })

  console.info(companyList.value)
}

const CJJGName = ref([])
// 获取承检机构名称
const getCJJGName = async () => {
  const res = await OrganizationQualificationApi.getOrganizationQualificationPage({pageNo:1,pageSize:1000})
  CJJGName.value = res.list
}

const rules = reactive({
  password: [{ validator: validatePassword, trigger: 'blur' },{ required: true, message: '请输入密码', trigger: 'blur' }],
  phone: [{ validator: validatePhone, trigger: 'blur' },{required: true, message: '请输入手机号', trigger: 'blur' },{max:20,message: '手机号长度不能超过20个字符', trigger: 'blur'}],
  email: [{ validator: validateEmail, trigger: 'blur' },{required: true, message: '请输入邮箱', trigger: 'blur' },{max:50,message: '邮箱长度不能超过50个字符', trigger: 'blur'}],
  password1: [{ validator: validatePasswordConfirm, trigger: 'blur' },{required: true, message: '请输入确认密码', trigger: 'blur' }],
  companyId:[{ required: true, message: '请输入单位', trigger: 'blur' },{ required: true, message: '请选择单位', trigger: 'change' },{max:30, message: '单位长度不能超过30个字符', trigger: 'blur' }],
  roleCode:[{ required: true, message: '请选择角色', trigger: 'change' }],
  name:[{required: true, message: '请输入姓名', trigger: 'blur' },{max:10, message: '姓名长度不能超过10个字符', trigger: 'blur' },{ pattern: /^[\u4e00-\u9fa5]+$/, message: '姓名只能为汉字', trigger: 'blur' }],
  loginName:[{required: true, message: '请输入登录名', trigger: 'blur' },{max:50, message: '登录名长度不能超过50个字符', trigger: 'blur' },  { pattern: /^[^\u4e00-\u9fa5]+$/, message: '登录名不能为汉字', trigger: 'blur' }],
  orgStaffId1:[{ required: true, message: '请选择单位', trigger: 'change' }],
  isValid:[{ required: true, message: '请选择是否有效', trigger: 'change' }],
  companyName:[{ required: true, message: '请选择单位', trigger: 'change' }],
})
const restaurants1 = ref([])

const YTList = ref<any>([])

const getYTList = async () => {
  const res = await ProjectManagemenrApi.getTreeListApi()
  YTList.value = dealTreeAddDisable(res, -1)
  restaurants1.value = companyList.value.map((item) => {
    return { value: item.name, id: item.id }
  })
}

const treeNodeAll = ref(false) // 全选/全不选

const querySearch1 = (queryString: string, cb: any) => {
  // restaurants.value.forEach((item,index)=>{
  //   item.value = item.id
  // })
  const results = queryString
    ? restaurants1.value.filter(createFilter(queryString))
    : restaurants1.value
  // call callback function to return suggestions
  cb(results)
}

const handleCompanyChange = (value) => {
  queryParams.value.companyId = value
  queryParams.value.name = ''
  getCJJGList(queryParams.value.companyId)
  
}

const handleCheckChange = () => {
  if (treeRef.value) {
    const keys = treeRef.value.getCheckedKeys()
    queryParams.value.menuIds = keys
  }
}

const handleCompanyChange1 = (value) => {
  queryParams.value.companyId = value
}

const getRoleListApi = async (id) => {
  const res = await UserInfoApi.getRoleList(id)
  console.log(res,'getRoleListApi')
  queryParams.value.menuIds = res
  let echoIds = res.filter(item=>item !=2772)
  const filterArr =  getLeafNodeIds(menuOptions.value)
  const arr = []
console.log(filterArr, 'echoIds')
filterArr.forEach((item)=>{
  echoIds.forEach((v)=>{
    if(item == v){
        arr.push(v)
    }
  })
})

  if (treeRef.value) {
    treeRef.value.setCheckedKeys(arr)
  }
// console.log(menuOptions.value,'menuOptions')
  
}

const loginDialog = ref(false)

const loginData = reactive({
  loginForm: {
    loginName: '',
    password: ''
  }
})

const updatePassword = (value) => {
  loginDialog.value = value
}

onMounted(() => {
  getDetail()
  getCJJGList()
  getCJJGName()
  getJFDW()
  getYTList()
  getRoleListApi1()
})


onActivated(() => {
  getDetail()
})
</script>

<template>
  <div>
    <ContentWrap>
      <el-form :rules="rules" ref="userRef"  :model="queryParams" inline label-width="120px" class="mt-20px">
        <el-card>
          <div class="user-info-cantainer">
            <span>用户信息</span>
            <div>
              <el-button type="primary" @click="handleAdd">保存</el-button>
              <el-button @click="goBack">返回</el-button>
            </div>
          </div>
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="用户角色" prop="roleCode">
                <el-select
                  @change="handleRoleChange"
                  v-model="queryParams.roleCode"
                 class="!w-240px"
                  placeholder="请选择用户角色"
                >
                  <el-option
                    v-for="(item, index) of roleList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8" v-if="queryParams.roleCode === 'org_user'">
              <el-form-item label="承检机构名称" prop="orgStaffId1">
                <el-select
                  class="!w-240px"
                  filterable
                  v-model="queryParams.orgStaffId1"
                  placeholder="请选择承检机构名称"
                  @change="handleCompanyChange"
                  :filter-method="handleFocus"
                >
                  <el-option
                    :label="item.name"
                    :value="Number(item.id)"
                    v-for="(item, index) of CJJGName"
                    :key="index"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8" v-if="queryParams.roleCode === 'first_party'">
              <el-form-item
                label="单位"
                prop="companyName"
                v-if="queryParams.roleCode === 'first_party'"
              >

              
              
                <el-tree-select
              v-model="queryParams.companyName"
              :data="YTList"
              clearable
              check-strictly
              style="width: 240px"
              :props="defaultProps1"
              @node-click="handleChangeTree"
            />
              </el-form-item>
            </el-col>


            <el-col
              :span="8"
              v-if="queryParams.roleCode === 'admin_qis' || queryParams.roleCode === 'third_party'"
            >
              <el-form-item label="单位" prop="companyId">
                <el-input class="!w-240px" v-model="queryParams.companyId" placeholder="请输入单位" />
                <!-- <input v-model="queryParams.a" /> -->
              </el-form-item>
            </el-col>
            <!-- 承检机构姓名 -->
            <el-col :span="8" v-if="queryParams.roleCode === 'org_user'">
              <el-form-item label="姓名" prop="name">
                <!-- <el-input v-model="queryParams.name" placeholder="请输入姓名" /> -->
                <el-autocomplete
                  v-model="queryParams.name"
                  :fetch-suggestions="querySearch"
                  clearable
                  class="inline-input !w-240px"
                  placeholder="请选择姓名"
                  @select="handleSelect"
                  @input="handleInput"
                  
                >
                  <template #suffix>
                    <i class="iconfont icon-sousuo search-style" @click="searchIcon"></i>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>

            <!-- 其他姓名 -->
            <el-col :span="8" v-else>
              <el-form-item label="姓名" prop="name">
                <el-input class="!w-240px" v-model="queryParams.name" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>


            <el-col :span="8">
              <el-form-item label="邮箱" prop="email">
                <el-input class="!w-240px" v-model="queryParams.email" placeholder="请输入邮箱" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="手机" prop="phone">
                <el-input class="!w-240px" v-model="queryParams.phone" placeholder="请输入手机" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="是否有效" prop="isValid">
                <el-select v-model="queryParams.isValid" class="!w-240px" placeholder="请选择是否有效">
                  <el-option
                    v-for="(item, index) of isValidList"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="登录名" prop="loginName">
                <el-input class="!w-240px" v-model="queryParams.loginName" placeholder="请输入登录名" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item
                label="密码"
                prop="password"
                style="margin-bottom: 50px"
                v-if="!queryParams.id"
              >
                <el-input class="!w-240px" v-model="queryParams.password" placeholder="按照集团密码规则设置" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="确认密码" prop="password1" v-if="!queryParams.id">
                <el-input class="!w-240px" v-model="queryParams.password1" placeholder="按照集团密码规则设置" />
              </el-form-item>
            </el-col>
 

            <el-col :span="8">
              <div class="flex justify-center items-center mb-5"
             
                ><el-checkbox
                  :true-value="1"
                  :false-value="0"
                  v-model="queryParams.isNextReset"
                  label="用户下次登录必须修改密码"
              /></div>
            </el-col>

            <el-col :span="8">
              <el-button  style="margin-left:120px" type="primary" v-if="queryParams.id" v-hasPermi="['qis:sys-user:unlock']"   @click="loginUnlock" >登录次数解锁</el-button>
            </el-col>
            <el-col :span="8">
              <el-button  style="margin-left:120px" type="primary" v-if="queryParams.id" @click="updatePassword"
                >重置密码</el-button
              >
            </el-col>

 
          </el-row>
        </el-card>

        <el-dialog v-model="loginDialog" title="修改密码">
          <el-form
            ref="formLogin"
            :model="loginData.loginForm"
            class="login-form"
            label-position="top"
            label-width="120px"
            size="large"
            :rules="dialogRules"
          >
            <el-row
              style="
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
              "
            >
              <el-col>
                <el-form-item prop="loginName">
                  <el-input
                    v-model="loginData.loginForm.loginName"
                    placeholder="用户名"
                    class="!w-240px"
                  >
                    <template #prefix>
                      <div class="input-icon-container">
                        <el-icon class="icon">
                          <component :is="iconAvatar" />
                        </el-icon>
                        <span class="text-black">账号</span>
                        <div class="divider"></div>
                      </div>
                    </template>
                  </el-input> </el-form-item
              ></el-col>
              <el-col>
                <el-form-item prop="password">
                  <el-input v-model="loginData.loginForm.password" placeholder="密码" class="!w-240px">
                    <template #prefix>
                      <div class="input-icon-container">
                        <el-icon class="icon">
                          <component :is="iconAvatar" />
                        </el-icon>
                        <span class="text-black">密码</span>
                        <div class="divider"></div>
                      </div>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item>
                  <el-button type="primary" class="!w100" @click="updateLogin">修改</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-dialog>

        <div class="mt-5">
          <el-card>
            <div class="user-info-cantainer">
              <span>权限配置</span>
            </div>
            <div class="m-10 ml-20">
              <el-form-item>
                <el-card class="w-full h-400px !overflow-y-scroll" shadow="never">
                  <template #header>
                    全选/全不选:
                    <el-switch
                      v-model="treeNodeAll"
                      active-text="是"
                      inactive-text="否"
                      inline-prompt
                      @change="handleCheckedTreeNodeAll"
                    />
                    全部展开/折叠:
                    <el-switch
                      v-model="menuExpand"
                      active-text="展开"
                      inactive-text="折叠"
                      inline-prompt
                      @change="handleCheckedTreeExpand"
                    />
                  </template>
                  <!--   :check-strictly="true" -->
                  <el-tree
                    ref="treeRef"
                    :data="menuOptions"
                    :props="defaultProps"
                    empty-text="加载中，请稍候"
                    node-key="id"
                    show-checkbox
                    :default-checked-keys="checkedKeys"
                    @check-change="handleCheckChange"
                  />
                </el-card>
              </el-form-item>
            </div>
          </el-card>
        </div>
      </el-form>
    </ContentWrap>
  </div>
</template>

<style lang="scss" scoped>
.user-info-cantainer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;

  span {
    font-size: 16px;
    font-weight: 600;
  }
}

.search-style {
  cursor: pointer;
}

/* 自定义样式，将校验提示信息显示在右侧 */
.el-form-item__error {
  position: absolute;
  top: 50%;
  right: 10px; /* 调整距离右侧的间距 */
  white-space: nowrap; /* 防止提示信息换行 */
  transform: translateY(-50%);
}

.el-form-item {
  position: relative; /* 为了让错误提示的绝对定位相对于表单项 */
}
</style>
